<template>
  <div class="app-container">
    <div class="main-layout">
      <!-- 左侧用能单元树 -->
      <div class="left-panel">
        <EnergyUnitTree
          ref="energyUnitTreeRef"
          title="用能单元结构"
          :show-node-actions="false"
          :show-expand-toggle="false"
          :auto-select-first="true"
          @node-click="handleNodeClick"
        />
      </div>

      <!-- 右侧分析内容 -->
      <div class="right-panel">
        <!-- 标题 -->
        <div class="analysis-header">
          <h2>历史数据趋势</h2>
        </div>

        <!-- 筛选区域 -->
        <div class="filter-section">
          <div class="filter-row">
            <!-- 日期筛选 -->
            <div class="date-filter">
              <el-date-picker
                v-model="selectedDate"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 200px"
              />
            </div>

            <!-- 设备选择 -->
            <div class="device-select">
              <el-select
                v-model="selectedDeviceId"
                placeholder="选择设备"
                clearable
                style="width: 200px"
                @change="handleDeviceChange"
              >
                <el-option
                  v-for="device in deviceList"
                  :key="device.deviceId"
                  :label="device.groupDeviceName || device.deviceName"
                  :value="device.deviceId"
                />
              </el-select>
            </div>

            <!-- 搜索按钮 -->
            <el-button type="primary" icon="Search" @click="handleSearch">
              搜索
            </el-button>
          </div>

          <!-- 属性标签选择 -->
          <div class="property-tags">
            <div class="tags-label">
              选择属性：
              <span style="color: #999; font-size: 12px">
                (设备属性数量: {{ deviceProperties.length }}, 选中数量:
                {{ selectedProperties.length }})
              </span>
            </div>
            <div class="tags-container" v-if="deviceProperties.length > 0">
              <el-checkbox-group
                v-model="selectedProperties"
                @change="handlePropertyChange"
              >
                <el-checkbox
                  v-for="property in deviceProperties"
                  :key="property.id"
                  :label="property"
                  :value="property"
                  class="property-checkbox"
                >
                  <span class="property-name">{{ property.name }}</span>
                  <span class="property-unit" v-if="property.dataDw"
                    >({{ property.dataDw }})</span
                  >
                </el-checkbox>
              </el-checkbox-group>
            </div>
            <div
              v-else-if="propertiesLoading"
              style="color: #999; font-size: 12px"
            >
              正在加载设备属性...
            </div>
            <div v-else style="color: #999; font-size: 12px">
              暂无设备属性数据
            </div>
          </div>
        </div>

        <!-- 内容区域 -->
        <div class="content-area">
          <!-- 图表区域 -->
          <div class="chart-container">
            <div
              ref="chartRef"
              class="chart"
              style="height: 400px"
              v-if="chartData.length > 0"
            ></div>
            <div class="chart-empty" v-else>
              <el-empty description="暂无数据" />
            </div>
          </div>

          <!-- 统计数据区域 -->
          <div class="statistics-container">
            <el-card class="stats-card">
              <div class="stats-grid">
                <!-- 数值类 -->
                <div class="stat-item">
                  <div class="stat-label">最大值</div>
                  <div class="stat-value">{{ statsValue.maxValue }}</div>
                </div>
                <div class="stat-item">
                  <div class="stat-label">最小值</div>
                  <div class="stat-value">{{ statsValue.minValue }}</div>
                </div>
                <div class="stat-item">
                  <div class="stat-label">平均值</div>
                  <div class="stat-value">{{ statsValue.avgValue }}</div>
                </div>

                <!-- 时间类 -->
                <div class="stat-item wide">
                  <div class="stat-label">最大值发生时间</div>
                  <div class="stat-time">{{ timeStats.maxTime }}</div>
                </div>
                <div class="stat-item wide">
                  <div class="stat-label">最小值发生时间</div>
                  <div class="stat-time">{{ timeStats.minTime }}</div>
                </div>
              </div>
            </el-card>
          </div>

          <!-- 数据表格区域 -->
          <div class="table-container" v-if="tableData.length > 0">
            <el-card class="table-card">
              <template #header>
                <div class="table-header">
                  <span>历史数据详情</span>
                </div>
              </template>
              <el-table :data="tableData" stripe style="width: 100%">
                <el-table-column prop="time" label="时间" width="120" />
                <el-table-column
                  v-for="property in selectedProperties"
                  :key="property.id"
                  :prop="property.dataCode"
                  :label="`${property.name}${
                    property.dataDw ? '(' + property.dataDw + ')' : ''
                  }`"
                >
                  <template #default="scope">
                    {{ (scope.row[property.dataCode] || 0).toFixed(2) }}
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import * as echarts from "echarts";
import { getDeviceGroupList } from "@/api/deviceManage/energyUnit";
import {
  getDeviceRealtimeData,
  getDeviceHistoryData,
} from "@/api/stat/realtime";
import EnergyUnitTree from "@/components/EnergyUnitTree/index.vue";

// 响应式数据
const selectedDate = ref("");
const selectedDeviceId = ref("");
const chartRef = ref(null);
const energyUnitTreeRef = ref(null);

// 用能单元和设备相关数据
const selectedNode = ref(null);
const deviceList = ref([]);
const deviceLoading = ref(false);

// 防重复调用标志
const isLoadingDevices = ref(false);

// 设备属性相关
const deviceProperties = ref([]);
const selectedProperties = ref([]);
const propertiesLoading = ref(false);

// 图表数据
const chartData = ref([]);

// 表格数据
const tableData = ref([]);

// 统计数据（卡片展示）
const statsValue = ref({ maxValue: "-", minValue: "-", avgValue: "-" });
const timeStats = ref({ maxTime: "-", minTime: "-" });

// 图表实例
let chartInstance = null;

// 方法
// 树相关函数
const handleNodeClick = (data) => {
  if (!data || !data.groupName) return;
  selectedNode.value = data;
  loadUnitDevices(data.groupId);
};

const loadUnitDevices = (groupId) => {
  if (!groupId) {
    deviceList.value = [];
    selectedDeviceId.value = "";
    deviceProperties.value = [];
    selectedProperties.value = [];
    chartData.value = [];
    tableData.value = [];
    statsValue.value = { maxValue: "-", minValue: "-", avgValue: "-" };
    timeStats.value = { maxTime: "-", minTime: "-" };

    // 清空图表
    if (chartInstance) {
      chartInstance.dispose();
      chartInstance = null;
    }
    return;
  }

  // 防重复调用 - 只有在相同groupId时才跳过
  if (isLoadingDevices.value && selectedNode.value?.groupId === groupId) {
    console.log("相同节点设备列表正在加载中，跳过重复调用");
    return;
  }

  // 切换用能单元时，先清空当前选中的设备和数据
  selectedDeviceId.value = "";
  deviceProperties.value = [];
  selectedProperties.value = [];
  chartData.value = [];
  tableData.value = [];
  statsValue.value = { maxValue: "-", minValue: "-", avgValue: "-" };
  timeStats.value = { maxTime: "-", minTime: "-" };

  // 清空图表
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }

  isLoadingDevices.value = true;
  deviceLoading.value = true;

  // 调用真实的设备接口
  getDeviceGroupList(groupId)
    .then((response) => {
      // 过滤掉虚表数据，只显示非虚表的数据
      const allDevices = response.data || [];
      deviceList.value = allDevices.filter((device) => device.isVirtual !== 1);

      // 默认选中第一个设备
      if (deviceList.value.length > 0) {
        selectedDeviceId.value = deviceList.value[0].deviceId;
        // 自动加载设备属性（不管是否有选中的日期）
        handleDeviceChange(deviceList.value[0].deviceId);
      }
      deviceLoading.value = false;
      isLoadingDevices.value = false;
    })
    .catch((error) => {
      console.error("获取分组设备失败:", error);
      deviceList.value = [];
      selectedDeviceId.value = "";
      deviceProperties.value = [];
      selectedProperties.value = [];
      chartData.value = [];
      tableData.value = [];
      statsValue.value = { maxValue: "-", minValue: "-", avgValue: "-" };
      timeStats.value = { maxTime: "-", minTime: "-" };

      // 清空图表
      if (chartInstance) {
        chartInstance.dispose();
        chartInstance = null;
      }

      deviceLoading.value = false;
      isLoadingDevices.value = false;
    });
};

const handleDeviceChange = (deviceId) => {
  if (!deviceId) {
    selectedDeviceId.value = "";
    deviceProperties.value = [];
    selectedProperties.value = [];
    chartData.value = [];
    tableData.value = [];

    // 清空图表
    if (chartInstance) {
      chartInstance.dispose();
      chartInstance = null;
    }
    return;
  }

  // 加载设备属性
  loadDeviceProperties(deviceId);

  // 设备切换时重新加载数据（如果有选中的日期和属性）
  if (selectedDate.value && selectedProperties.value.length > 0) {
    loadData();
  }
};

// 加载设备属性
const loadDeviceProperties = async (deviceId) => {
  if (!deviceId) return;

  console.log("开始加载设备属性，deviceId:", deviceId);
  propertiesLoading.value = true;
  try {
    const response = await getDeviceRealtimeData(deviceId);
    console.log("设备属性API响应:", response);

    if (response.data && response.data.proPertyList) {
      // 只取 kind 为 1 的数据属性
      deviceProperties.value = response.data.proPertyList.filter(
        (prop) => prop.kind === 1
      );
      console.log("过滤后的数据属性:", deviceProperties.value);

      // 默认选中第一个属性
      if (deviceProperties.value.length > 0) {
        selectedProperties.value = [deviceProperties.value[0]];
        console.log("默认选中的属性:", selectedProperties.value);

        // 如果有选中的日期，自动加载数据
        if (selectedDate.value) {
          console.log("自动加载历史数据");
          loadData();
        }
      }
    } else {
      console.log("API响应中没有proPertyList");
      deviceProperties.value = [];
      selectedProperties.value = [];
    }
  } catch (error) {
    console.error("获取设备属性失败:", error);
    deviceProperties.value = [];
    selectedProperties.value = [];
  } finally {
    propertiesLoading.value = false;
  }
};

const handleSearch = () => {
  if (!selectedDate.value) {
    ElMessage.warning("请选择日期");
    return;
  }
  if (!selectedDeviceId.value) {
    ElMessage.warning("请选择设备");
    return;
  }
  if (selectedProperties.value.length === 0) {
    ElMessage.warning("请选择至少一个属性");
    return;
  }

  loadData();
};

// 属性选择变化
const handlePropertyChange = () => {
  if (
    selectedDate.value &&
    selectedDeviceId.value &&
    selectedProperties.value.length > 0
  ) {
    loadData();
  }
};

// 加载数据
const loadData = async () => {
  if (!selectedDeviceId.value || selectedProperties.value.length === 0) {
    return;
  }

  try {
    // 计算时间范围：当天00:00:00到当天23:59:59
    const startOfDay = Math.floor(
      new Date(selectedDate.value + " 00:00:00").getTime() / 1000
    ); // 当天0点，转换为秒
    const endOfDay = Math.floor(
      new Date(selectedDate.value + " 23:59:59").getTime() / 1000
    ); // 当天23:59:59，转换为秒

    console.log("时间范围计算:", {
      selectedDate: selectedDate.value,
      startOfDay: startOfDay,
      endOfDay: endOfDay,
      startTime: new Date(startOfDay * 1000).toLocaleString(),
      endTime: new Date(endOfDay * 1000).toLocaleString(),
    });

    // 构建tag参数（多个属性用逗号分割）
    const tags = selectedProperties.value
      .map((prop) => prop.dataCode)
      .join(",");

    const params = {
      deviceId: selectedDeviceId.value,
      tags: tags,
      start: startOfDay,
      end: endOfDay,
      curPage: 1,
      pagesize: 1000, // 获取足够多的数据
    };

    const response = await getDeviceHistoryData(params);

    if (
      response.data &&
      response.data.dataList &&
      response.data.dataList.list
    ) {
      // 处理API返回的数据，先倒序排列（因为第一条是最新时间）
      const processedData = response.data.dataList.list
        .reverse()
        .map((item) => {
          const result = {
            time: formatTimeForChart(item.date, item.dateStr),
            timestamp: item.date,
          };

          // 为每个选中的属性添加数据
          selectedProperties.value.forEach((prop) => {
            const value =
              item.data && item.data[prop.dataCode]
                ? item.data[prop.dataCode]
                : 0;
            result[prop.dataCode] =
              parseFloat(value) * (prop.dataMultiple || 1);
          });

          return result;
        });

      chartData.value = processedData;
      tableData.value = processedData;

      // 更新统计数据
      updateStatistics();

      // 重新渲染图表
      nextTick(() => {
        initChart();
      });
    } else {
      chartData.value = [];
      tableData.value = [];
      ElMessage.info("暂无历史数据");
    }
  } catch (error) {
    console.error("加载数据失败:", error);
    ElMessage.error("加载数据失败");
  }
};

// 格式化时间用于图表显示（只显示小时和分钟）
const formatTimeForChart = (timestamp, dateStr = null) => {
  // 优先使用 dateStr 字段
  if (dateStr) {
    // 解析 dateStr 格式，如 "2025-10-10 10" 或 "2025-10-10 10:30"
    const parts = dateStr.split(" ");
    if (parts.length >= 2) {
      const timePart = parts[1];
      if (timePart.includes(":")) {
        // 如果包含分钟，直接返回
        return timePart;
      } else {
        // 如果只有小时，补全分钟为00
        return `${timePart.padStart(2, "0")}:00`;
      }
    }
  }

  // 如果没有 dateStr 或解析失败，使用时间戳
  if (!timestamp) return "--";

  let date;

  // 如果是字符串格式的日期（如 "2025-10-01"）
  if (typeof timestamp === "string") {
    // 如果只有日期没有时间，添加默认时间
    if (timestamp.length === 10) {
      timestamp += " 00:00:00";
    }
    date = new Date(timestamp);
  } else {
    // 如果是数字时间戳
    const ms = timestamp > 1e12 ? timestamp / 1e6 : timestamp;
    date = new Date(ms);
  }

  // 检查日期是否有效
  if (isNaN(date.getTime())) {
    return "--";
  }

  return date.toLocaleString("zh-CN", {
    hour: "2-digit",
    minute: "2-digit",
  });
};

// 获取当前选中设备信息
const getCurrentDevice = () => {
  return deviceList.value.find(
    (device) => device.deviceId === selectedDeviceId.value
  );
};

// 更新统计数据
const updateStatistics = () => {
  if (chartData.value.length === 0) return;

  // 计算第一个选中属性的统计数据
  if (selectedProperties.value.length > 0) {
    const firstProperty = selectedProperties.value[0];
    const values = chartData.value.map(
      (item) => item[firstProperty.dataCode] || 0
    );
    const maxValue = Math.max(...values);
    const minValue = Math.min(...values);
    const avgValue = values.reduce((sum, val) => sum + val, 0) / values.length;

    // 找到最大最小值的发生时间
    const maxItem = chartData.value.find(
      (item) => item[firstProperty.dataCode] === maxValue
    );
    const minItem = chartData.value.find(
      (item) => item[firstProperty.dataCode] === minValue
    );

    statsValue.value = {
      maxValue: maxValue.toFixed(2),
      minValue: minValue.toFixed(2),
      avgValue: avgValue.toFixed(2),
    };

    timeStats.value = {
      maxTime: maxItem ? maxItem.time : "-",
      minTime: minItem ? minItem.time : "-",
    };
  }
};

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;

  if (chartInstance) {
    chartInstance.dispose();
  }

  chartInstance = echarts.init(chartRef.value);

  // 构建系列数据
  const series = selectedProperties.value.map((prop, index) => {
    const colors = [
      "#4fdaca",
      "#ff6b6b",
      "#4ecdc4",
      "#45b7d1",
      "#96ceb4",
      "#feca57",
    ];
    return {
      name: prop.name,
      type: "line",
      data: chartData.value.map((item) => item[prop.dataCode] || 0),
      smooth: true,
      lineStyle: {
        color: colors[index % colors.length],
      },
      itemStyle: {
        color: colors[index % colors.length],
      },
    };
  });

  const option = {
    title: {
      text: "历史数据趋势",
      left: "center",
    },
    tooltip: {
      trigger: "axis",
      formatter: function (params) {
        let result = `${params[0].axisValue}<br/>`;
        params.forEach((param) => {
          result += `${param.seriesName}: ${param.value}<br/>`;
        });
        return result;
      },
    },
    legend: {
      data: selectedProperties.value.map((prop) => prop.name),
      top: 30,
    },
    xAxis: {
      type: "category",
      data: chartData.value.map((item) => item.time),
    },
    yAxis: {
      type: "value",
      name: "数值",
      axisLabel: {
        formatter: "{value}",
      },
    },
    series: series,
  };

  chartInstance.setOption(option);

  // 响应式调整
  window.addEventListener("resize", () => {
    chartInstance?.resize();
  });
};

// 页面初始化
onMounted(() => {
  // 设置默认日期为今天
  const today = new Date();
  selectedDate.value = today.toISOString().split("T")[0];
  // 树组件会自动加载数据
});
</script>

<style lang="scss" scoped>
@import "@/assets/styles/variables.module.scss";

.app-container {
  padding: 0;
  background: $base-menu-background;
  height: 100%;
  overflow: hidden;
}

.main-layout {
  display: flex;
  gap: 15px;
  padding: 10px;
  height: 100%;
  box-sizing: border-box;
  overflow: hidden;
}

// 左侧面板
.left-panel {
  flex: 0 0 300px;
  min-width: 250px;
  max-width: 350px;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

// 右侧面板
.right-panel {
  flex: 1;
  min-width: 0;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;

  .analysis-header {
    padding: 20px 30px;
    border-bottom: 1px solid #e4e7ed;
    background: #f8f9fa;

    h2 {
      font-size: 20px;
      font-weight: 600;
      color: #2c3e50;
      margin: 0;
    }
  }

  .filter-section {
    padding: 20px 30px;
    border-bottom: 1px solid #e4e7ed;

    .filter-row {
      display: flex;
      align-items: center;
      gap: 20px;
      margin-bottom: 15px;

      .date-filter,
      .device-select {
        :deep(.el-input__wrapper) {
          border-radius: 6px;
          transition: all 0.3s ease;

          &:focus-within {
            box-shadow: 0 0 0 2px rgba(79, 218, 202, 0.2);
          }
        }
      }

      .el-button {
        border-radius: 6px;
        font-weight: 500;
        padding: 8px 20px;

        &.el-button--primary {
          background: linear-gradient(135deg, #4fdaca 0%, #32b7cb 100%);
          border: none;
          color: #ffffff;

          &:hover {
            background: linear-gradient(135deg, #3bc4b3 0%, #2aa3b8 100%);
            color: #ffffff;
          }
        }
      }
    }

    .property-tags {
      .tags-label {
        font-size: 14px;
        color: #606266;
        margin-bottom: 10px;
        font-weight: 500;
      }

      .tags-container {
        :deep(.el-checkbox-group) {
          display: flex;
          flex-wrap: wrap;
          gap: 12px;
        }

        .property-checkbox {
          :deep(.el-checkbox__label) {
            display: flex;
            align-items: center;
            gap: 4px;
            font-size: 13px;

            .property-name {
              font-weight: 500;
              color: #2c3e50;
            }

            .property-unit {
              color: #909399;
              font-size: 12px;
            }
          }

          :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
            background-color: #4fdaca;
            border-color: #4fdaca;
          }
        }
      }
    }
  }

  .content-area {
    flex: 1;
    padding: 20px 30px;
    display: flex;
    flex-direction: column;
    overflow-y: auto;

    .chart-container {
      flex: 1;
      margin-bottom: 20px;

      .chart {
        width: 100%;
        border-radius: 8px;
        background: #ffffff;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }

      .chart-empty {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 400px;
        background: #f8f9fa;
        border-radius: 8px;
        border: 1px dashed #d9d9d9;
      }
    }

    .statistics-container {
      margin-bottom: 20px;

      .stats-card {
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

        :deep(.el-card__body) {
          padding: 20px;
        }

        .stats-grid {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
          gap: 16px;

          .stat-item {
            padding: 16px;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-radius: 8px;
            border: 1px solid #e4e7ed;

            &.wide {
              grid-column: span 2;
            }

            .stat-label {
              font-size: 14px;
              color: #6c757d;
              margin-bottom: 8px;
              font-weight: 500;
            }

            .stat-value {
              font-size: 22px;
              font-weight: 700;
              color: #2c3e50;
            }

            .stat-time {
              font-size: 14px;
              color: #2c3e50;
            }
          }
        }
      }
    }

    .table-container {
      .table-card {
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

        :deep(.el-card__header) {
          background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
          border-bottom: 1px solid #e4e7ed;

          .table-header {
            font-size: 16px;
            font-weight: 600;
            color: #2c3e50;
          }
        }

        :deep(.el-table) {
          .el-table__header {
            th {
              background: #f8f9fa;
              color: #2c3e50;
              font-weight: 600;
            }
          }

          .el-table__row {
            &:hover {
              background: #f0f8ff;
            }
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .main-layout {
    flex-direction: column;
  }

  .left-panel {
    width: 100%;
    height: 200px;
    border-right: none;
    border-bottom: 1px solid #e4e7ed;
  }

  .right-panel {
    height: calc(100vh - 200px);
  }
}

@media (max-width: 768px) {
  .right-panel {
    .filter-section {
      padding: 15px;

      .filter-row {
        flex-direction: column;
        align-items: stretch;
        gap: 15px;

        .date-filter,
        .device-select {
          width: 100%;
        }
      }
    }

    .content-area {
      padding: 15px;
    }
  }
}
</style>
